#!/usr/bin/env python
# coding=utf-8
from google.appengine.ext.webapp import RequestHandler
from google.appengine.api.datastore_types import GeoPt
from google.appengine.api import datastore_errors
from api import WriteJson
from geo import geohash
from config import LOCATION_PRECISION
from google.appengine.ext import db, webapp
from google.appengine.ext.webapp import util
from v2ex.babel.security import get_current_member

class QueryLocalUsers(RequestHandler):
    def post(self):
        member = get_current_member
        if member is not False:
            try:
                location = GeoPt(self.request.get("location"))
#                location = GeoPt(22.4869863614,113.904884338)
            except datastore_errors.BadValueError, err:
                WriteJson(self, {"result":False,"message":err.message}, "normalResult.json")
                return
            percision = 6
            if self.request.get('percision'):
                percision = int(self.request.get('percision'))
            if percision>11:
                percision = 11
            elif percision<3:
                percision = 3
            hash_location = geohash.encode(location.lat, location.lon, 12)
            hash_location = hash_location[0:percision]
            neighbors = self.get_neighbors(hash_location[0:LOCATION_PRECISION],percision)
            template = {}
            template["members"] = []
            neighbors.sort()
            loactions = db.GqlQuery('SELECT * FROM Location WHERE hash_location >= :1 AND hash_location <= :2',neighbors[0],neighbors[-1])
            for location in loactions:
                memb = {}
                memb['member'] = location.member
                memb['location'] = location.location
                template["members"].append(memb)
            WriteJson(self, template, 'members.json')
        else:
            self.redirect('/signin')
            
    def get_neighbors(self,hash_location,percision):
        result = geohash.expand(hash_location)
        i = 6
        while i>percision:
            temp = result[:]
            for area in temp:
                neighbors = geohash.neighbors(area)
                for neighbor in neighbors:
                    if result.count(neighbor) < 1:
                        result.append(neighbor)
            i-=1
        return result   
    
    def get(self):
        self.post()
         
def main():
    application = webapp.WSGIApplication([('/user/querylocalusers',QueryLocalUsers)],
                                         debug=True)
    util.run_wsgi_app(application)
        
if __name__ == '__main__':
    main()